<template>
  <div>
    <div class="down-bth">
      <el-input v-model="dataInfo.username" placeholder="搜索名称" class="input-with-select" style="width: 20%;" @input="searChto">
        <template #append>
          <el-button icon="Search" />
        </template>
      </el-input>
      <el-button type="danger" icon="Plus" @click="adduserFn">新增账户</el-button>
    </div>
    <el-table style="width: 90%;margin: 10px auto" :data="tableData" border :header-cell-style="{
      background: '#E7F2FF',
      color: 'black',
    }" v-loading="loading">
      <el-table-column type="index" label="序号" :index="indexMethod" width="80" />
      <el-table-column prop="level" label="级别" width="100" />
      <el-table-column prop="username" label="用户名称" width="300" />
      <el-table-column prop="develop" label="开发区名称" width="300" />
      <el-table-column prop="createTime" label="创建时间" width="200" />
      <el-table-column prop="labelOne" label="标签1" width="150" />
      <el-table-column prop="labelTwo" label="标签2" width="150" />
      <el-table-column prop="labelThree" label="标签3" width="150" />
      <el-table-column label="操作" align="center" min-width="100" width="auto" fixed="right">
        <template #default="scope">
          <el-button type="info" icon="Edit" size="small" @click="openEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination :total="totals" layout="prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" v-model:current-page="dataInfo.currentPage"
        v-model::page-size="dataInfo.pageNum" />
    </div>
  </div>
  <el-dialog v-model="dialogFormVisible" :title="titles" draggable @close="handleClose">
    <el-form label-position="right" label-width="100px" :model="activeItem" style="width: 100%;" ref="ruleFormRef"
      :rules="rules">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="activeItem.username" placeholder="请输入名称" style="width: 80%;" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="activeItem.password" placeholder="请输入密码" show-password style="width: 80%;" />
      </el-form-item>
      <el-form-item label="类型" prop="checkValue" v-if="titles=='新增'">
        <el-cascader :options="optionType" v-model="activeItem.checkValue" @change="changeSelect" clearable  filterable
          popper-class="last-check" :props="props" />
      </el-form-item>
      <!-- <el-form-item label="级别" prop="level">
        <el-select v-model="activeItem.level" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="标签1">
        <el-input v-model="activeItem.labelOne" placeholder="请输入标签1" style="width:214px" />
      </el-form-item>
      <el-form-item label="标签2">
        <el-input v-model="activeItem.labelTwo" placeholder="请输入标签2" style="width:214px" />
        <!-- <el-select v-model="activeItem.labelTwo" placeholder="请选择标签2">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
      </el-form-item>
      <el-form-item label="标签3">
        <el-input v-model="activeItem.labelThree" placeholder="请输入标签3" style="width:214px" />
        <!-- <el-select v-model="activeItem.labelThree" placeholder="请选择标签3">
          <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false;getList()">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { userFindByList, userupdate, userSaveUser, getAllTB } from "@/util/api";
const loading: any = ref(false)
const dialogFormVisible: any = ref(false)
const tableData: any = ref([])
const totals: any = ref(0)
const ruleFormRef = ref<FormInstance>();
const titles: any = ref('编辑')
const shareScope: any = ref('-1')
const activeItem: any = ref({

})
let timer  = null
const props: any = ref({
  multiple: true,
  checkStrictly: false
})
const optionType: any = ref([
  // {
  //   value: '1',
  //   label: '省级',
  //   children: []
  // },
  {
    value: '2',
    label: '市级',
    children: [],
  },
  {
    value: '3',
    label: '区级',
    children: [
      {
        value: '1',
        label: '普通报表用户',
      },
      //   {
      //     value: '2',
      //     label: '园中区报表用户',
      //   },
    ],
  },
])
const option: any = ref([
  {
    value: '县域经开区',
    label: '县域经开区',
  },
])
const options: any = ref([
  {
    value: '国家级',
    label: '国家级',
  },
  {
    value: '省级',
    label: '省级',
  },
  {
    value: '市级',
    label: '市级',
  },
  {
    value: '区级',
    label: '区级',
  },
  {
    value: '县级',
    label: '县级',
  },
])
// 类型改变
const changeSelect = (value: any) => {
  console.log(value)
  // 是否与上次的类型相同
  for (var i = 0; i < value.length; i++) {
        if (value[i][0] !== shareScope.value) {
          shareScope.value = value[i][0]
          break
        }
      }
      const filterd = value.filter((v:any) => v[0] === shareScope.value)
      activeItem.value.checkValue = []
      activeItem.value.checkValue.push(...filterd)
      console.log(activeItem.value.checkValue)
  }
  //打开新增
  const adduserFn = async () => {
    // console.log(optionType.value)
    //获取区级目录
    let res: any = await getAllTB("")
    console.log(res)
    if (res.code != 200) return
    res.data.forEach((item: any) => {
      let data = {
        label: item.username,
        value: item.id
      }
      optionType.value[0].children.push(data)
    });
    activeItem.value = {}
    dialogFormVisible.value = true
    titles.value = '新增'
  }
  const dataInfo: any = ref({
    username: "",
    team: "",
    page: 1,
    pageSize: 10,
    labelOne: ""
  })
  const indexMethod = (index: number) => {
    return index + ((dataInfo.value.page - 1) * dataInfo.value.pageSize) + 1
  }
  const handleClose = () => {
    activeItem.value = {}
  }
  const rules = reactive({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    level: [
      { required: true, message: '请选择级别', trigger: 'change' },
    ],
    newpassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请再次输入新密码', trigger: 'blur' },
    ],
    checkValue:[
    {  type: 'array',
      required: true,
      message: '请选择类型',
      trigger: 'change', },
    ]
  })
  //确定更改和新增
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (!valid) return
      if (titles.value == '新增') {
        activeItem.value['userType']=''
        activeItem.value['shUserId']=''
        activeItem.value.userRole=activeItem.value.checkValue[0][0]
        if(activeItem.value.checkValue[0].length>1){             
              if(activeItem.value.checkValue[0][0]=='2'){
                activeItem.value['shUserId']=[]
                activeItem.value.checkValue.forEach((v:any)=>{
                  activeItem.value['shUserId'].push(v[1])
                })
                activeItem.value['shUserId']=activeItem.value['shUserId'].join(",")
              }else{
                activeItem.value['userType']=activeItem.value.checkValue[0][1]
              }
        }
        console.log(activeItem.value)
        let res: any = await userSaveUser(activeItem.value)
        activeItem.value={}
        dialogFormVisible.value = false
        console.log(res)
        if(res.code != 200) return
        ElMessage({
            message: '创建成功！',
            type: 'success',
          })
        getList();
      } else {
        if (activeItem.value.oldPassWord == activeItem.value.password) activeItem.value.oldPassWord = null
        let result: any = await userupdate(activeItem.value)
        if (result.code != 200) return
        dialogFormVisible.value = false
        ElMessage({
            message: '修改成功！',
            type: 'success',
          })
      }
    })
  }
  //获取账户列表
  const getList = async () => {
    loading.value=true
    let res: any = await userFindByList(dataInfo.value)
    console.log(res)
    if (res.code != 200) return
    totals.value = res.data.totalElements
    tableData.value = res.data.content
    loading.value=false
  }
  const searChto=()=>{
    loading.value=true
    if(timer!==null){
      clearTimeout(timer)
    }
    timer = setTimeout(()=>{ 
      getList()
    },500)
    
  }
  //分页
  const handleSizeChange = (val: number) => {
    dataInfo.value.pageSize = val;
    getList();
  };
  const handleCurrentChange = (val: number) => {
    dataInfo.value.page = val;
    getList();
  };
  //编辑
  const openEdit = (row: any) => {
    dialogFormVisible.value = true
    titles.value = '编辑'
    activeItem.value = row
    activeItem.value.oldPassWord = JSON.parse(JSON.stringify(row.password))
  }
  onMounted(() => {
    getList()
  })
</script>
<style lang="scss" scoped>
.down-bth {
  width: 90%;
  margin: 20px auto;
  display: flex;
  justify-content: space-between;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.pagination-box {
  width: 90%;
  margin: 30px auto;

  ::v-deep(.el-pagination) {
    float: right;
  }
}
</style>
<style lang="scss">
.el-cascader-panel {
  .el-scrollbar:first-child {
    .el-checkbox {
      display: none;
    }
  }
}
</style>